"""
场景服务层 - 实现组合模式的场景管理
"""

from typing import List, Optional

from sqlalchemy.orm import Session

try:
    from ..pojo.ai_web_scene import (
        AIWebScene, AIWebSceneCreate, AIWebSceneUpdate,
        AIWebSceneResponse, AIWebSceneTreeResponse,
        AIWebSceneQueryParams, SceneStatus
    )
    from ..pojo.ai_web_scene_model import AIWebSceneModel
    from ..scene.scene_repository import SceneRepository
except ImportError:
    from pojo.ai_web_scene import (
        AIWebScene, AIWebSceneCreate, AIWebSceneUpdate,
        AIWebSceneResponse, AIWebSceneTreeResponse,
        AIWebSceneQueryParams, SceneStatus
    )
    from pojo.ai_web_scene_model import AIWebSceneModel
    from scene.scene_repository import SceneRepository


class SceneService:
    """场景服务类 - 实现组合模式的场景管理"""

    def __init__(self, db: Session):
        self.db = db
        self.repository = SceneRepository(db)

    def _model_to_response(self, model: AIWebSceneModel, include_children: bool = True) -> AIWebSceneResponse:
        """将数据库模型转换为响应模型"""
        response = AIWebSceneResponse(
            scene_id=model.scene_id,
            scene_name=model.scene_name,
            description=model.description,
            parent_id=model.parent_id,
            node_path=model.node_path,
            node_level=model.node_level,
            sort_order=model.sort_order,
            scene_status=model.scene_status,
            creator=model.creator,
            create_time=model.create_time,
            modifier=model.modifier,
            modify_time=model.modify_time,
            version=model.version,
            children=[]
        )

        if include_children and model.children:
            response.children = [
                self._model_to_response(child, include_children)
                for child in sorted(model.children, key=lambda x: x.sort_order)
            ]

        return response

    def get_scene_tree(self, query_params: AIWebSceneQueryParams) -> AIWebSceneTreeResponse:
        """获取场景树结构"""
        # 从数据库获取根节点
        root_models = self.repository.get_root_nodes(query_params)

        # 转换为响应模型
        response_nodes = [
            self._model_to_response(root, query_params.include_children)
            for root in root_models
        ]

        # 计算统计信息
        total_count = self.repository.count_all(query_params)
        max_depth = self.repository.get_max_depth()

        return AIWebSceneTreeResponse(
            total_count=total_count,
            max_depth=max_depth,
            root_nodes=response_nodes
        )

    def get_scene_by_id(self, scene_id: str) -> Optional[AIWebSceneResponse]:
        """根据ID获取场景"""
        model = self.repository.get_by_id(scene_id)
        if not model:
            return None
        return self._model_to_response(model, include_children=False)

    def get_children_by_parent_id(self, parent_id: str) -> List[AIWebSceneResponse]:
        """根据父节点ID获取子节点列表"""
        children_models = self.repository.get_children(parent_id)
        return [
            self._model_to_response(child, include_children=False)
            for child in children_models
        ]

    def get_scene_path(self, scene_id: str) -> List[AIWebSceneResponse]:
        """获取场景路径（从根节点到当前节点）"""
        path_models = self.repository.get_scene_path(scene_id)
        return [
            self._model_to_response(model, include_children=False)
            for model in path_models
        ]

    def create_scene(self, scene_create: AIWebSceneCreate) -> AIWebSceneResponse:
        """创建新场景"""
        scene_data = {
            'scene_name': scene_create.scene_name,
            'description': scene_create.description,
            'parent_id': scene_create.parent_id,
            'sort_order': scene_create.sort_order,
            'scene_status': scene_create.scene_status,
            'creator': scene_create.creator
        }

        created_model = self.repository.create(scene_data)
        return self._model_to_response(created_model, include_children=False)

    def update_scene(self, scene_id: str, scene_update: AIWebSceneUpdate) -> Optional[AIWebSceneResponse]:
        """更新场景"""
        update_data = {
            'scene_name': scene_update.scene_name,
            'description': scene_update.description,
            'sort_order': scene_update.sort_order,
            'scene_status': scene_update.scene_status,
            'modifier': scene_update.modifier,
            'version': scene_update.version
        }

        # 移除None值
        update_data = {k: v for k, v in update_data.items() if v is not None}

        try:
            updated_model = self.repository.update(scene_id, update_data)
            if not updated_model:
                return None
            return self._model_to_response(updated_model, include_children=False)
        except ValueError as e:
            raise e

    def delete_scene(self, scene_id: str) -> bool:
        """删除场景（级联删除子节点）"""
        return self.repository.delete(scene_id)

    def move_scene(self, scene_id: str, new_parent_id: Optional[str]) -> Optional[AIWebSceneResponse]:
        """移动场景到新的父节点"""
        try:
            moved_model = self.repository.move_scene(scene_id, new_parent_id)
            if not moved_model:
                return None
            return self._model_to_response(moved_model, include_children=False)
        except ValueError as e:
            raise e
